import { login as loginAPI } from '@/api'
import { getToken, setToken, removeToken } from '@/utils/auth'
// 引入路由
import { anyRoute, asyncRoutes, constantRoutes } from '@/router/routes'
// 引入router
import router from '@/router'
import {resetRouter} from '@/router'//引入重置路由
import cloneDeep from 'lodash/cloneDeep'//深拷贝

// 封装过滤异步路由
// asyncRoutes 异步路由  routes用户路由
function filterasyncRoutes(asyncRoutes, routes) {
  //  过滤路由
  return asyncRoutes.filter(item => {
    // 过滤出一级路由
    if (routes.indexOf(item.name) != -1) {
      // 过滤出二级路由
      if (item.children && item.children.length > 0) {

        item.children = filterasyncRoutes(item.children, routes)
      }
      return true
    }
  })
}

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',

    roles: [],
    buttons: [],
    routes: [], // 本用户所有的路由,包括了固定的路由和下面的addRouters
    asyncRoutes: [] // 本用户的角色赋予的新增的动态路由

  }
}

const state = getDefaultState()

const mutations = {
  SET_USER: (state, userInfo) => {
    state.name = userInfo.name // 用户名
    state.avatar = userInfo.avatar // 头像
    state.roles = userInfo.roles // 角色列表
    state.buttons = userInfo.buttons // 按钮权限列表
  },

  SET_TOKEN(state, token) {
    state.token = token
  },

  RESET_USER(state) {
    Object.assign(state, getDefaultState())
  },
  // 需要的动态路由
  SET_ROUTER(state,asyncRoutes){
   state.asyncRoutes=asyncRoutes
  //  添加任意路由和异步路由
  state.routes=constantRoutes.concat(asyncRoutes,anyRoute)
  router.addRoutes([...asyncRoutes,anyRoute])
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      loginAPI.login(username, password)
        .then(result => {
          const { data } = result
          commit('SET_TOKEN', data.token)
          setToken(data.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  async getInfo({ commit, state }) {
    const { data } = await loginAPI.getInfo()
    commit('SET_USER', data)
    // 通知仓库需要添加的动态路由
    commit('SET_ROUTER',filterasyncRoutes(cloneDeep(asyncRoutes), data.routes))
  },

  /* 
  重置用户信息
  */
  async resetUser({ commit, state }) {
    // 如果当前是登陆的, 请求退出登陆
    if (state.name) {
      await loginAPI.logout()
    }
    // 删除local中保存的token
    removeToken()
    // 重置路由
    resetRouter()
    // 提交重置用户信息的mutation
    commit('RESET_USER')
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}